<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 7.0.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon.ico">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon.ico">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">


<link rel="stylesheet" href="/lib/font-awesome/css/all.min.css">
  <link rel="stylesheet" href="/lib/pace/pace-theme-minimal.min.css">
  <script src="/lib/pace/pace.min.js"></script>

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"jjbond.cn","root":"/","scheme":"Gemini","version":"7.8.0","exturl":false,"sidebar":{"position":"right","width":300,"display":"post","padding":18,"offset":12,"onmobile":false,"sidebar_rss":{"text":"RSS","icon":"fa fa-rss","color":"burlywood","link":"atom.xml"}},"copycode":{"enable":true,"show_result":true,"style":"mac"},"back2top":{"enable":true,"sidebar":false,"scrollpercent":true},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":true,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"search.xml"};
  </script>

  <meta name="description" content="这个 App 实现的效果是通过OMDB API来搜索电影并将结果展现给用户。搭建这个 App 的过程能帮助我们很好的学习React Hooks的用法，练习实际项目能帮助更快上手。 App 完成后的效果预览">
<meta property="og:type" content="article">
<meta property="og:title" content="用React Hooks搭建一个电影搜索App">
<meta property="og:url" content="https://jjbond.cn/posts/13078.html">
<meta property="og:site_name" content="吉吉邦德">
<meta property="og:description" content="这个 App 实现的效果是通过OMDB API来搜索电影并将结果展现给用户。搭建这个 App 的过程能帮助我们很好的学习React Hooks的用法，练习实际项目能帮助更快上手。 App 完成后的效果预览">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://i.imgtg.com/2023/07/13/OzZvvc.md.png">
<meta property="og:image" content="https://i.imgtg.com/2023/07/12/Ozh9w6.md.png">
<meta property="article:published_time" content="2023-07-12T07:55:35.000Z">
<meta property="article:modified_time" content="2023-07-13T08:33:12.188Z">
<meta property="article:author" content="右眼">
<meta property="article:tag" content="Web">
<meta property="article:tag" content="React">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://i.imgtg.com/2023/07/13/OzZvvc.md.png">

<link rel="canonical" href="https://jjbond.cn/posts/13078.html">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>用React Hooks搭建一个电影搜索App | 吉吉邦德</title>

  <!-- 球形气泡标签云 -->
  <script type="text/javascript" src="/js/bubble.js"></script>

  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

<link rel="alternate" href="/atom.xml" title="吉吉邦德" type="application/atom+xml">
</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>
      <a target="_blank" rel="noopener" href="https://github.com/Neopo1itan/" class="github-corner" aria-label="View source on GitHub"><svg width="80" height="80" viewBox="0 0 250 250" style="fill:#1f3e5c; color:#fff; position: absolute; top: 0; border: 0; right: 0;" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a ><style>.github-corner:hover .octo-arm{animation:octocat-wave 560ms ease-in-out}@keyframes octocat-wave{0%,100%{transform:rotate(0)}20%,60%{transform:rotate(-25deg)}40%,80%{transform:rotate(10deg)}}@media (max-width:500px){.github-corner:hover .octo-arm{animation:none}.github-corner .octo-arm{animation:octocat-wave 560ms ease-in-out}}</style>
    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">吉吉邦德</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-regular fa-desktop fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="fa fa-regular fa-tags fa-fw"></i>标签<span class="badge">7</span></a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="fa fa-regular fa-shapes fa-fw"></i>分类<span class="badge">6</span></a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="fa fa-regular fa-inbox fa-fw"></i>归档<span class="badge">18</span></a>

  </li>
        <li class="menu-item menu-item-rss">

    <a href="/atom.xml" rel="section"><i class="fa fa-rss fa-fw"></i>RSS</a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup">
        <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result">
  <div id="no-result">
    <i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>
  </div>
</div>

    </div>
  </div>

</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://jjbond.cn/posts/13078.html">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.png">
      <meta itemprop="name" content="右眼">
      <meta itemprop="description" content="任何时间 任何地点<br>超级侦探 认真办案">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="吉吉邦德">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          用React Hooks搭建一个电影搜索App
        </h1>

        <div class="post-meta">
          
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2023-07-12 15:55:35" itemprop="dateCreated datePublished" datetime="2023-07-12T15:55:35+08:00">2023-07-12</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="far fa-calendar-check"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2023-07-13 16:33:12" itemprop="dateModified" datetime="2023-07-13T16:33:12+08:00">2023-07-13</time>
              </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/%E5%89%8D%E7%AB%AF%E5%BC%80%E5%8F%91/" itemprop="url" rel="index"><span itemprop="name">前端开发</span></a>
                </span>
            </span>

          <br>
            <span class="post-meta-item" title="本文字数">
              <span class="post-meta-item-icon">
                <i class="far fa-file-word"></i>
              </span>
                <span class="post-meta-item-text">本文字数：</span>
              <span>10k</span>
            </span>
            <span class="post-meta-item" title="阅读时长">
              <span class="post-meta-item-icon">
                <i class="far fa-clock"></i>
              </span>
                <span class="post-meta-item-text">阅读时长 &asymp;</span>
              <span>9 分钟</span>
            </span>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <p>这个 App 实现的效果是通过<strong>OMDB API</strong>来搜索电影并将结果展现给用户。搭建这个 App 的过程能帮助我们很好的学习<strong>React Hooks</strong>的用法，练习实际项目能帮助更快上手。</p>
<h3 id="App-完成后的效果预览"><a href="#App-完成后的效果预览" class="headerlink" title="App 完成后的效果预览"></a>App 完成后的效果预览</h3><p><a target="_blank" rel="noopener" href="https://imgtg.com/image/OzZvvc"><img data-src="" data-original="https://i.imgtg.com/2023/07/13/OzZvvc.md.png" alt="OzZvvc.md.png"></a></p>
<span id="more"></span>
<h3 id="项目用到的工具"><a href="#项目用到的工具" class="headerlink" title="项目用到的工具"></a>项目用到的工具</h3><ul>
<li>Node</li>
<li>VsCode</li>
<li>OMDB 的 API key (<a target="_blank" rel="noopener" href="http://www.omdbapi.com/apikey.aspx">这里获得</a>)</li>
</ul>
<p>准备好上述工具后，我们需要用 react 的脚手架工具来帮助我们搭建一个全新的 React 应用程序，安装<strong>create-react-app</strong>脚手架：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">npm i -g create-react-app</span><br><span class="line">//或者用cnpm yarn都可以</span><br></pre></td></tr></table></figure>

<p>然后通过脚手架新建项目:</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">create-react-app movie-search-app</span><br></pre></td></tr></table></figure>

<p>完成之后用 VsCode 打开该目录，目录结构如下图所示：<br><a target="_blank" rel="noopener" href="https://imgtg.com/image/Ozh9w6"><img data-src="" data-original="https://i.imgtg.com/2023/07/12/Ozh9w6.md.png" alt="structure"></a></p>
<h3 id="构成该-App-的-4-个组件"><a href="#构成该-App-的-4-个组件" class="headerlink" title="构成该 App 的 4 个组件"></a>构成该 App 的 4 个组件</h3><ul>
<li><strong>App.js</strong> —— 它是其它 3 个组件的父组件，将包含处理 API 请求的函数以及组件初始化时调用的 API</li>
<li><strong>Header.js</strong> —— 接受参数并展示 App 的标题</li>
<li><strong>Movie.js</strong> —— 渲染每个电影，电影对象将通过参数传递给它</li>
<li><strong>Search.js</strong> —— 包含一个带有输入和搜索按钮的表单，处理输入和重置的函数以及一个作为参数传递给它的搜索函数</li>
</ul>
<h3 id="开始着手构建我们的-APP"><a href="#开始着手构建我们的-APP" class="headerlink" title="开始着手构建我们的 APP"></a>开始着手构建我们的 APP</h3><p>在<code>src</code>目录下新建一个文件夹命名为<code>components</code>(之后所有组件都将保存在这个地方)，然后把<code>App.js</code>组件移动到该目录下。新建一个<code>Header.js</code>组件用于展示程序的标题，并加入如下代码：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// Header.js</span></span><br><span class="line"><span class="keyword">import</span> <span class="title class_">React</span> <span class="keyword">from</span> <span class="string">&quot;react&quot;</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> <span class="title function_">Header</span> = (<span class="params">props</span>) =&gt; &#123;</span><br><span class="line">  <span class="keyword">return</span> (</span><br><span class="line">    <span class="language-xml"><span class="tag">&lt;<span class="name">header</span> <span class="attr">className</span>=<span class="string">&quot;App-header&quot;</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">      <span class="tag">&lt;<span class="name">h2</span>&gt;</span>&#123;props.text&#125;<span class="tag">&lt;/<span class="name">h2</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">    <span class="tag">&lt;/<span class="name">header</span>&gt;</span></span></span><br><span class="line">  );</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> <span class="title class_">Header</span>;</span><br></pre></td></tr></table></figure>

<p>更新<code>src</code>目录下<code>index.js</code>中的导入</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//index.js</span></span><br><span class="line"><span class="keyword">import</span> <span class="title class_">App</span> <span class="keyword">from</span> <span class="string">&#x27;./components/App&#x27;</span>;</span><br></pre></td></tr></table></figure>

<p>并且更新<code>App.css</code>中的样式代码(供参考)：</p>
<figure class="highlight css"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br></pre></td><td class="code"><pre><span class="line"><span class="selector-class">.App</span> &#123;</span><br><span class="line">  <span class="attribute">text-align</span>: center;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="selector-class">.App-header</span> &#123;</span><br><span class="line">  <span class="attribute">background-color</span>: <span class="number">#282c34</span>;</span><br><span class="line">  <span class="attribute">height</span>: <span class="number">70px</span>;</span><br><span class="line">  <span class="attribute">display</span>: flex;</span><br><span class="line">  <span class="attribute">flex-direction</span>: column;</span><br><span class="line">  <span class="attribute">align-items</span>: center;</span><br><span class="line">  <span class="attribute">justify-content</span>: center;</span><br><span class="line">  <span class="attribute">font-size</span>: <span class="built_in">calc</span>(<span class="number">10px</span> + <span class="number">2vmin</span>);</span><br><span class="line">  <span class="attribute">color</span>: white;</span><br><span class="line">  <span class="attribute">padding</span>: <span class="number">20px</span>;</span><br><span class="line">  <span class="attribute">cursor</span>: pointer;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="selector-class">.spinner</span> &#123;</span><br><span class="line">  <span class="attribute">height</span>: <span class="number">80px</span>;</span><br><span class="line">  <span class="attribute">margin</span>: auto;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="selector-class">.App-intro</span> &#123;</span><br><span class="line">  <span class="attribute">font-size</span>: large;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/* new css for movie component */</span></span><br><span class="line">* &#123;</span><br><span class="line">  <span class="attribute">box-sizing</span>: border-box;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="selector-class">.movies</span> &#123;</span><br><span class="line">  <span class="attribute">display</span>: flex;</span><br><span class="line">  <span class="attribute">flex-wrap</span>: wrap;</span><br><span class="line">  <span class="attribute">flex-direction</span>: row;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="selector-class">.App-header</span> <span class="selector-tag">h2</span> &#123;</span><br><span class="line">  <span class="attribute">margin</span>: <span class="number">0</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="selector-class">.add-movies</span> &#123;</span><br><span class="line">  <span class="attribute">text-align</span>: center;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="selector-class">.add-movies</span> <span class="selector-tag">button</span> &#123;</span><br><span class="line">  <span class="attribute">font-size</span>: <span class="number">16px</span>;</span><br><span class="line">  <span class="attribute">padding</span>: <span class="number">8px</span>;</span><br><span class="line">  <span class="attribute">margin</span>: <span class="number">0</span> <span class="number">10px</span> <span class="number">30px</span> <span class="number">10px</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="selector-class">.movie</span> &#123;</span><br><span class="line">  <span class="attribute">padding</span>: <span class="number">5px</span> <span class="number">25px</span> <span class="number">10px</span> <span class="number">25px</span>;</span><br><span class="line">  <span class="attribute">max-width</span>: <span class="number">25%</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="selector-class">.errorMessage</span> &#123;</span><br><span class="line">  <span class="attribute">margin</span>: auto;</span><br><span class="line">  <span class="attribute">font-weight</span>: bold;</span><br><span class="line">  <span class="attribute">color</span>: <span class="built_in">rgb</span>(<span class="number">161</span>, <span class="number">15</span>, <span class="number">15</span>);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="selector-class">.search</span> &#123;</span><br><span class="line">  <span class="attribute">display</span>: flex;</span><br><span class="line">  <span class="attribute">flex-direction</span>: row;</span><br><span class="line">  <span class="attribute">flex-wrap</span>: wrap;</span><br><span class="line">  <span class="attribute">justify-content</span>: center;</span><br><span class="line">  <span class="attribute">margin-top</span>: <span class="number">10px</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="selector-tag">input</span><span class="selector-attr">[type=<span class="string">&quot;submit&quot;</span>]</span> &#123;</span><br><span class="line">  <span class="attribute">padding</span>: <span class="number">5px</span>;</span><br><span class="line">  <span class="attribute">background-color</span>: transparent;</span><br><span class="line">  <span class="attribute">color</span>: black;</span><br><span class="line">  <span class="attribute">border</span>: <span class="number">1px</span> solid black;</span><br><span class="line">  <span class="attribute">width</span>: <span class="number">80px</span>;</span><br><span class="line">  <span class="attribute">margin-left</span>: <span class="number">5px</span>;</span><br><span class="line">  <span class="attribute">cursor</span>: pointer;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="selector-tag">input</span><span class="selector-attr">[type=<span class="string">&quot;submit&quot;</span>]</span><span class="selector-pseudo">:hover</span> &#123;</span><br><span class="line">  <span class="attribute">background-color</span>: <span class="number">#282c34</span>;</span><br><span class="line">  <span class="attribute">color</span>: antiquewhite;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="selector-class">.search</span> &gt; <span class="selector-tag">input</span><span class="selector-attr">[type=<span class="string">&quot;text&quot;</span>]</span>&#123;</span><br><span class="line">  <span class="attribute">width</span>: <span class="number">40%</span>;</span><br><span class="line">  <span class="attribute">min-width</span>: <span class="number">170px</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">@media</span> screen <span class="keyword">and</span> (<span class="attribute">min-width</span>: <span class="number">694px</span>) <span class="keyword">and</span> (<span class="attribute">max-width</span>: <span class="number">915px</span>) &#123;</span><br><span class="line">  <span class="selector-class">.movie</span> &#123;</span><br><span class="line">    <span class="attribute">max-width</span>: <span class="number">33%</span>;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">@media</span> screen <span class="keyword">and</span> (<span class="attribute">min-width</span>: <span class="number">652px</span>) <span class="keyword">and</span> (<span class="attribute">max-width</span>: <span class="number">693px</span>) &#123;</span><br><span class="line">  <span class="selector-class">.movie</span> &#123;</span><br><span class="line">    <span class="attribute">max-width</span>: <span class="number">50%</span>;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">@media</span> screen <span class="keyword">and</span> (<span class="attribute">max-width</span>: <span class="number">651px</span>) &#123;</span><br><span class="line">  <span class="selector-class">.movie</span> &#123;</span><br><span class="line">    <span class="attribute">max-width</span>: <span class="number">100%</span>;</span><br><span class="line">    <span class="attribute">margin</span>: auto;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><font color="gray" size=2>随时可以用<font color=#C4244D size=2>npm start</font>启动项目来查看效果</font></p>
<p>下一步创建<code>Movie.js</code>组件，代码如下</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//Movie.js</span></span><br><span class="line"><span class="keyword">import</span> <span class="title class_">React</span> <span class="keyword">from</span> <span class="string">&quot;react&quot;</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> <span class="variable constant_">DEFAULT_PLACEHOLDER_IMAGE</span> = </span><br><span class="line"><span class="string">&quot;https://m.media-amazon.com/images/M/MV5BMTczNTI2ODUwOF5BMl5BanBnXkFtZTcwMTU0NTIzMw@@._V1_SX300.jpg&quot;</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> <span class="title function_">Movie</span> = (<span class="params">&#123;movie&#125;</span>) =&gt; &#123;</span><br><span class="line">    <span class="comment">//不存在则展示默认图片</span></span><br><span class="line">    <span class="keyword">const</span> poster = movie.<span class="property">Poster</span> === <span class="string">&quot;N/A&quot;</span>? <span class="variable constant_">DEFAULT_PLACEHOLDER_IMAGE</span> : movie.<span class="property">Poster</span>;</span><br><span class="line">    <span class="keyword">return</span>(</span><br><span class="line">        <span class="language-xml"><span class="tag">&lt;<span class="name">div</span> <span class="attr">className</span>=<span class="string">&quot;movie&quot;</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">            <span class="tag">&lt;<span class="name">h2</span>&gt;</span>&#123;movie.Title&#125;<span class="tag">&lt;/<span class="name">h2</span>&gt;</span>//展示电影标题</span></span><br><span class="line"><span class="language-xml">            <span class="tag">&lt;<span class="name">div</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">                <span class="tag">&lt;<span class="name">img</span> <span class="attr">src</span>=<span class="string">&#123;poster&#125;</span> <span class="attr">alt</span>=<span class="string">&#123;</span>`<span class="attr">The</span> <span class="attr">movie</span> <span class="attr">titled:</span>$&#123;<span class="attr">movie.Title</span>&#125;`&#125; <span class="attr">width</span>=<span class="string">&quot;200&quot;</span> /&gt;</span></span></span><br><span class="line"><span class="language-xml">            <span class="tag">&lt;/<span class="name">div</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">            <span class="tag">&lt;<span class="name">p</span>&gt;</span>(&#123;movie.Year&#125;)<span class="tag">&lt;/<span class="name">p</span>&gt;</span>//展示电影年份</span></span><br><span class="line"><span class="language-xml">        <span class="tag">&lt;/<span class="name">div</span>&gt;</span></span></span><br><span class="line">    )</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> <span class="title class_">Movie</span>;</span><br></pre></td></tr></table></figure>

<p>接下来开始创建<code>Search</code>组件。这是最关键的一部分，因为使用Hooks之前的React为了处理内部状态需要创建一个类组件…不过现在利用Hooks可以在函数组件内部处理自己的状态。在<code>components</code>文件夹下新建<code>Search.js</code>文件并加入如下代码：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//Search.js</span></span><br><span class="line"><span class="keyword">import</span> <span class="title class_">React</span>, &#123; useState &#125; <span class="keyword">from</span> <span class="string">&quot;react&quot;</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> <span class="title function_">Search</span> = (<span class="params">props</span>) =&gt; &#123;</span><br><span class="line">    <span class="keyword">const</span> [searchValue, setSearchValue] = <span class="title function_">useState</span>(<span class="string">&#x27;&#x27;</span>);</span><br><span class="line">    <span class="keyword">const</span> <span class="title function_">handleSearchInputChanges</span> = (<span class="params">e</span>) =&gt; &#123;</span><br><span class="line">        <span class="title function_">setSearchValue</span>(e.<span class="property">target</span>.<span class="property">value</span>);<span class="comment">//修改搜索值</span></span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">const</span> <span class="title function_">resetInputField</span> = (<span class="params"></span>) =&gt; &#123;</span><br><span class="line">        <span class="title function_">setSearchValue</span>(<span class="string">&#x27;&#x27;</span>);<span class="comment">//重置搜索</span></span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">const</span> <span class="title function_">callSearchFunction</span> = (<span class="params">e</span>) =&gt; &#123;</span><br><span class="line">        e.<span class="title function_">preventDefault</span>();<span class="comment">//阻止默认操作</span></span><br><span class="line">        props.<span class="title function_">search</span>(searchValue);<span class="comment">//调用搜索</span></span><br><span class="line">        <span class="title function_">resetInputField</span>();<span class="comment">//调用重置函数</span></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span>(</span><br><span class="line">        <span class="language-xml"><span class="tag">&lt;<span class="name">form</span> <span class="attr">className</span>=<span class="string">&quot;search&quot;</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">            <span class="tag">&lt;<span class="name">input</span> <span class="attr">type</span>=<span class="string">&quot;text&quot;</span> <span class="attr">value</span>=<span class="string">&#123;searchValue&#125;</span> <span class="attr">onChange</span>=<span class="string">&#123;handleSearchInputChanges&#125;/</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">            <span class="tag">&lt;<span class="name">input</span> <span class="attr">type</span>=<span class="string">&quot;submit&quot;</span> <span class="attr">value</span>=<span class="string">&quot;SEARCH&quot;</span> <span class="attr">onClick</span>=<span class="string">&#123;callSearchFunction&#125;</span> /&gt;</span></span></span><br><span class="line"><span class="language-xml">        <span class="tag">&lt;/<span class="name">form</span>&gt;</span></span></span><br><span class="line">    )</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> <span class="title class_">Search</span>;</span><br></pre></td></tr></table></figure>

<h3 id="Hooks-API-useState介绍"><a href="#Hooks-API-useState介绍" class="headerlink" title="Hooks API - useState介绍"></a>Hooks API - useState介绍</h3><blockquote>
<p>在<code>Search.js</code>组件中使用了一个<strong>hooks API</strong>，即<strong>useState</strong>。顾名思义它允许我们向函数组件添加React状态。<strong>useState</strong>钩子接收一个初始状态参数，并返回一个数组包含当前的状态（<em>this.state</em>）和一个更新它的函数（<em>this.setState</em>）。<br>在我们的示例中，我们将当前状态作为搜索输入值传递。在输入框触发onChange事件时，将调用<em>handleSearchInputChanges</em>函数用于更新输入的搜索值。<em>resetInputField</em>方法用于清空当前搜索框的值。(<a target="_blank" rel="noopener" href="https://legacy.reactjs.org/docs/hooks-state.html">更多useState内容</a>)</p>
</blockquote>
<p>接下来让我们更新<code>App.js</code>中的代码</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//App.js</span></span><br><span class="line"><span class="keyword">import</span> <span class="title class_">React</span>, &#123; useEffect, useState &#125; <span class="keyword">from</span> <span class="string">&quot;react&quot;</span></span><br><span class="line"><span class="keyword">import</span> <span class="string">&#x27;./App.css&#x27;</span>;</span><br><span class="line"><span class="keyword">import</span> <span class="title class_">Header</span> <span class="keyword">from</span> <span class="string">&#x27;./Header&#x27;</span>;</span><br><span class="line"><span class="keyword">import</span> <span class="title class_">Movie</span> <span class="keyword">from</span> <span class="string">&#x27;./Movie&#x27;</span>;</span><br><span class="line"><span class="keyword">import</span> <span class="title class_">Search</span> <span class="keyword">from</span> <span class="string">&#x27;./Search&#x27;</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> <span class="variable constant_">MOVIE_API_URL</span> = <span class="string">&quot;https://www.omdbapi.com/?s=man&amp;apikey=4a3b711b&quot;</span>; <span class="comment">// 用自己的替换</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> <span class="title function_">App</span> = (<span class="params"></span>) =&gt; &#123;</span><br><span class="line">  <span class="keyword">const</span> [loading, setLoading] = <span class="title function_">useState</span>(<span class="literal">true</span>);<span class="comment">//加载状态</span></span><br><span class="line">  <span class="keyword">const</span> [movies, setMovies] = <span class="title function_">useState</span>([]);<span class="comment">//电影列表</span></span><br><span class="line">  <span class="keyword">const</span> [errorMessage,setErrorMessage] = <span class="title function_">useState</span>(<span class="literal">null</span>);<span class="comment">//错误信息</span></span><br><span class="line"></span><br><span class="line">  <span class="title function_">useEffect</span>(<span class="function">()=&gt;</span>&#123;</span><br><span class="line">    <span class="title function_">fetch</span>(<span class="variable constant_">MOVIE_API_URL</span>).<span class="title function_">then</span>(<span class="function"><span class="params">response</span> =&gt;</span> response.<span class="title function_">json</span>()).<span class="title function_">then</span>(<span class="function"><span class="params">jsonResponse</span> =&gt;</span> &#123;</span><br><span class="line">      <span class="title function_">setMovies</span>(jsonResponse.<span class="property">Search</span>);</span><br><span class="line">      <span class="title function_">setLoading</span>(<span class="literal">false</span>);</span><br><span class="line">    &#125;);</span><br><span class="line">  &#125;,[]);</span><br><span class="line"></span><br><span class="line">  <span class="keyword">const</span> <span class="title function_">search</span> = searchValue =&gt; &#123;<span class="comment">//搜索方法</span></span><br><span class="line">    <span class="title function_">setLoading</span>(<span class="literal">true</span>);</span><br><span class="line">    <span class="title function_">setErrorMessage</span>(<span class="literal">null</span>)</span><br><span class="line"></span><br><span class="line">    <span class="title function_">fetch</span>(<span class="string">`https://www.omdbapi.com/?s=<span class="subst">$&#123;searchValue&#125;</span>&amp;apikey=4a3b711b`</span>)</span><br><span class="line">        .<span class="title function_">then</span>(<span class="function"><span class="params">response</span> =&gt;</span> response.<span class="title function_">json</span>())</span><br><span class="line">        .<span class="title function_">then</span>(<span class="function"><span class="params">jsonResponse</span> =&gt;</span> &#123;</span><br><span class="line">            <span class="keyword">if</span>(jsonResponse.<span class="property">Response</span> === <span class="string">&quot;True&quot;</span>)&#123;</span><br><span class="line">                <span class="title function_">setMovies</span>(jsonResponse.<span class="property">Search</span>);</span><br><span class="line">                <span class="title function_">setLoading</span>(<span class="literal">false</span>);</span><br><span class="line">            &#125;<span class="keyword">else</span>&#123;</span><br><span class="line">                <span class="title function_">setErrorMessage</span>(jsonResponse.<span class="property">Error</span>);</span><br><span class="line">                <span class="title function_">setLoading</span>(<span class="literal">false</span>);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;);</span><br><span class="line">  &#125;;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">return</span>(</span><br><span class="line">    <span class="language-xml"><span class="tag">&lt;<span class="name">div</span> <span class="attr">className</span>=<span class="string">&#x27;App&#x27;</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">      <span class="tag">&lt;<span class="name">Header</span> <span class="attr">text</span>=<span class="string">&quot;MovieSearchApp&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">Header</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">      <span class="tag">&lt;<span class="name">Search</span> <span class="attr">search</span>=<span class="string">&#123;search&#125;</span>&gt;</span><span class="tag">&lt;/<span class="name">Search</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">      <span class="tag">&lt;<span class="name">p</span> <span class="attr">className</span>=<span class="string">&#x27;App-intro&#x27;</span>&gt;</span>分享一些喜欢的电影<span class="tag">&lt;/<span class="name">p</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">      <span class="tag">&lt;<span class="name">div</span> <span class="attr">className</span>=<span class="string">&#x27;movies&#x27;</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">        &#123; loading&amp;&amp;!errorMessage?(</span></span><br><span class="line"><span class="language-xml">        <span class="tag">&lt;<span class="name">span</span>&gt;</span>loading...<span class="tag">&lt;/<span class="name">span</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">        ):errorMessage?(</span></span><br><span class="line"><span class="language-xml">        <span class="tag">&lt;<span class="name">div</span> <span class="attr">className</span>=<span class="string">&#x27;errorMessage&#x27;</span>&gt;</span>&#123;errorMessage&#125;<span class="tag">&lt;/<span class="name">div</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">        ):(</span></span><br><span class="line"><span class="language-xml">          movies.map((movie,index) =&gt; (</span></span><br><span class="line"><span class="language-xml">            <span class="tag">&lt;<span class="name">Movie</span> <span class="attr">key</span>=<span class="string">&#123;</span>`$&#123;<span class="attr">index</span>&#125;<span class="attr">-</span>$&#123;<span class="attr">movie.Title</span>&#125;`&#125; <span class="attr">movie</span>=<span class="string">&#123;movie&#125;/</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">          ))</span></span><br><span class="line"><span class="language-xml">        )&#125;</span></span><br><span class="line"><span class="language-xml">      <span class="tag">&lt;/<span class="name">div</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">    <span class="tag">&lt;/<span class="name">div</span>&gt;</span></span></span><br><span class="line">  );</span><br><span class="line">&#125;;</span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> <span class="title class_">App</span>;</span><br></pre></td></tr></table></figure>

<p>在上述代码中，我们用到了3个<strong>useState</strong>函数，第一个函数用于处理当前加载状态；第二个函数用于处理从服务器获取的电影数组；第三个函数用于处理API请求时可能返回的错误信息。</p>
<p>然后我们用到了第二种hooks API：<strong>useEffect</strong><br>这个钩子基本上能让你在函数组件中执行副作用，副作用指的是例如数据获取，订阅和手动操作DOM这类事情。这个钩子最棒的一部分来自官方文档的介绍：</p>
<blockquote>
<p>如果你熟悉React的类的生命周期方法，你可以将useEffect看作componentDidMout，componentDidUpdate和componentWillUnmount的结合。</p>
</blockquote>
<p>这是因为<strong>useEffect</strong>会在第一次渲染（componentDidMount）之后和每次更新（componentDidUpdate）之后进行调用。</p>
<p>你可能想知道如果它在每次更新之后都进行调用，那么它和componentDidMount有何相似的地方？那是因为这个函数接受两个参数，一个是你想要运行的函数另一个是数组。在该数组中我们只需要传入一个值去告诉React如果该值没有修改则跳过应用的函数效果。</p>
<p>根据文档，这和我们在componentDidUpdate中添加一个if判断语句类似：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//for class components</span></span><br><span class="line"><span class="title function_">componentDidUpdate</span>(<span class="params">prevProps, prevState</span>) &#123;</span><br><span class="line">    <span class="keyword">if</span>(prevState.<span class="property">count</span> !== <span class="variable language_">this</span>.<span class="property">state</span>.<span class="property">count</span>)&#123;</span><br><span class="line">        <span class="variable language_">document</span>.<span class="property">title</span> = <span class="string">`You clicked <span class="subst">$&#123;<span class="variable language_">this</span>.state.count&#125;</span> times`</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//for hooks</span></span><br><span class="line"><span class="title function_">useEffect</span>(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">    <span class="variable language_">document</span>.<span class="property">title</span> = <span class="string">`You clicked <span class="subst">$&#123;count&#125;</span> times`</span>;</span><br><span class="line">&#125;,[count]);<span class="comment">// 只有count改变了才会再执行</span></span><br></pre></td></tr></table></figure>

<p>在我们的代码中初始化时并没有要改变的值，所以可以传入一个空数组来告诉React这个方法需要调用一次。</p>
<p>如你所见，我们有三个存在一定联系的<strong>useState</strong>函数，所以它们应该可以用某种方式组合起来。因此React为我们提供了另一个hook——<strong>useReducer</strong>。利用这个钩子我们的代码变成如下所示：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> initialState = &#123;</span><br><span class="line">  <span class="attr">loading</span>:<span class="literal">true</span>,</span><br><span class="line">  <span class="attr">movies</span>:[],</span><br><span class="line">  <span class="attr">errorMessage</span>:<span class="literal">null</span></span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">const</span> <span class="title function_">reducer</span> = (<span class="params">state,action</span>) =&gt; &#123;</span><br><span class="line">  <span class="keyword">switch</span>(action.<span class="property">type</span>)&#123;</span><br><span class="line">    <span class="keyword">case</span> <span class="string">&quot;SEARCH_MOVIES_REQUEST&quot;</span>:</span><br><span class="line">      <span class="keyword">return</span>&#123;</span><br><span class="line">        ...state,</span><br><span class="line">        <span class="attr">loading</span>:<span class="literal">true</span>,</span><br><span class="line">        <span class="attr">errorMessage</span>:<span class="literal">null</span></span><br><span class="line">      &#125;;</span><br><span class="line">    <span class="keyword">case</span> <span class="string">&quot;SEARCH_MOVIES_SUCCESS&quot;</span>:</span><br><span class="line">      <span class="keyword">return</span>&#123;</span><br><span class="line">        ...state,</span><br><span class="line">        <span class="attr">loading</span>:<span class="literal">false</span>,</span><br><span class="line">        <span class="attr">movies</span>:action.<span class="property">payload</span></span><br><span class="line">      &#125;;</span><br><span class="line">    <span class="keyword">case</span> <span class="string">&quot;SEARCH_MOVIES_FAILURE&quot;</span>:</span><br><span class="line">      <span class="keyword">return</span>&#123;</span><br><span class="line">        ...state,</span><br><span class="line">        <span class="attr">loading</span>:<span class="literal">false</span>,</span><br><span class="line">        <span class="attr">movies</span>:action.<span class="property">error</span></span><br><span class="line">      &#125;;</span><br><span class="line">    <span class="attr">default</span>:</span><br><span class="line">      <span class="keyword">return</span> state;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;;</span><br><span class="line"><span class="keyword">const</span> <span class="title function_">App</span> = (<span class="params"></span>) =&gt; &#123;</span><br><span class="line">  <span class="keyword">const</span> [state,dispatch] = <span class="title function_">useReducer</span>(reducer,initialState);</span><br><span class="line">  <span class="title function_">useEffect</span>(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">    <span class="title function_">fetch</span>(<span class="variable constant_">MOVIE_API_URL</span>)</span><br><span class="line">      .<span class="title function_">then</span>(<span class="function"><span class="params">response</span> =&gt;</span> response.<span class="title function_">json</span>())</span><br><span class="line">      .<span class="title function_">then</span>(<span class="function"><span class="params">jsonResponse</span> =&gt;</span> &#123;</span><br><span class="line">        <span class="title function_">dispatch</span>(&#123;</span><br><span class="line">          <span class="attr">type</span>:<span class="string">&quot;SEARCH_MOVIES_SUCCESS&quot;</span>,</span><br><span class="line">          <span class="attr">payload</span>:jsonResponse.<span class="property">Search</span></span><br><span class="line">        &#125;);</span><br><span class="line">      &#125;);</span><br><span class="line">  &#125;,[]);</span><br><span class="line"></span><br><span class="line">  <span class="keyword">const</span> <span class="title function_">search</span> = searchValue =&gt; &#123;<span class="comment">//搜索方法</span></span><br><span class="line">    <span class="title function_">dispatch</span>(&#123;</span><br><span class="line">      <span class="attr">type</span>:<span class="string">&quot;SEARCH_MOVIES_REQUEST&quot;</span></span><br><span class="line">    &#125;);</span><br><span class="line">    <span class="title function_">fetch</span>(<span class="string">`https://www.omdbapi.com/?s=<span class="subst">$&#123;searchValue&#125;</span>&amp;apikey=4a3b711b`</span>)</span><br><span class="line">      .<span class="title function_">then</span>(<span class="function"><span class="params">response</span> =&gt;</span> response.<span class="title function_">json</span>())</span><br><span class="line">      .<span class="title function_">then</span>(<span class="function"><span class="params">jsonResponse</span> =&gt;</span> &#123;</span><br><span class="line">        <span class="keyword">if</span>(jsonResponse.<span class="property">Response</span> === <span class="string">&quot;True&quot;</span>)&#123;</span><br><span class="line">          <span class="title function_">dispatch</span>(&#123;</span><br><span class="line">            <span class="attr">type</span>:<span class="string">&quot;SEARCH_MOVIES_SUCCESS&quot;</span>,</span><br><span class="line">            <span class="attr">payload</span>:jsonResponse.<span class="property">Search</span></span><br><span class="line">          &#125;);</span><br><span class="line">        &#125;<span class="keyword">else</span>&#123;</span><br><span class="line">          <span class="title function_">dispatch</span>(&#123;</span><br><span class="line">            <span class="attr">type</span>:<span class="string">&quot;SEARCH_MOVIES_FAILURE&quot;</span>,</span><br><span class="line">            <span class="attr">error</span>:jsonResponse.<span class="property">Error</span></span><br><span class="line">          &#125;);</span><br><span class="line">        &#125;</span><br><span class="line">      &#125;);</span><br><span class="line">  &#125;;</span><br><span class="line"><span class="keyword">const</span> &#123; movies, errorMessage, loading&#125; = state;</span><br><span class="line">  <span class="keyword">return</span>(</span><br><span class="line">    <span class="language-xml"><span class="tag">&lt;<span class="name">div</span> <span class="attr">className</span>=<span class="string">&#x27;App&#x27;</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">      <span class="tag">&lt;<span class="name">Header</span> <span class="attr">text</span>=<span class="string">&quot;MovieSearchApp&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">Header</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">      <span class="tag">&lt;<span class="name">Search</span> <span class="attr">search</span>=<span class="string">&#123;search&#125;</span>&gt;</span><span class="tag">&lt;/<span class="name">Search</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">      <span class="tag">&lt;<span class="name">p</span> <span class="attr">className</span>=<span class="string">&#x27;App-intro&#x27;</span>&gt;</span>分享一些喜欢的电影<span class="tag">&lt;/<span class="name">p</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">      <span class="tag">&lt;<span class="name">div</span> <span class="attr">className</span>=<span class="string">&#x27;movies&#x27;</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">        &#123; loading&amp;&amp;!errorMessage?(</span></span><br><span class="line"><span class="language-xml">        <span class="tag">&lt;<span class="name">span</span>&gt;</span>loading...<span class="tag">&lt;/<span class="name">span</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">        ):errorMessage?(</span></span><br><span class="line"><span class="language-xml">        <span class="tag">&lt;<span class="name">div</span> <span class="attr">className</span>=<span class="string">&#x27;errorMessage&#x27;</span>&gt;</span>&#123;errorMessage&#125;<span class="tag">&lt;/<span class="name">div</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">        ):(</span></span><br><span class="line"><span class="language-xml">          movies.map((movie,index) =&gt; (</span></span><br><span class="line"><span class="language-xml">            <span class="tag">&lt;<span class="name">Movie</span> <span class="attr">key</span>=<span class="string">&#123;</span>`$&#123;<span class="attr">index</span>&#125;<span class="attr">-</span>$&#123;<span class="attr">movie.Title</span>&#125;`&#125; <span class="attr">movie</span>=<span class="string">&#123;movie&#125;/</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">          ))</span></span><br><span class="line"><span class="language-xml">        )&#125;</span></span><br><span class="line"><span class="language-xml">      <span class="tag">&lt;/<span class="name">div</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">    <span class="tag">&lt;/<span class="name">div</span>&gt;</span></span></span><br><span class="line">  );</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<p><strong>useReducer</strong>钩子接受3个参数，不过我们只使用了其中2个。一个典型的用力如下：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> [state, dispatch] = <span class="title function_">useReducer</span>(reducer,initialState);</span><br></pre></td></tr></table></figure>

<p>在我们的代码中，reducer接收我们定义的initialState对象和一系列操作，基于操作的类型返回给我们新的状态对象。例如我们的操作类型是”<strong>SEARCH_MOVIES_REQUEST</strong>“，状态将更新为”loading&#x3D;true,errorMessage&#x3D;null”。</p>
<p>另一件需要注意的事情是，在<strong>useEffect</strong>中，我们将从服务器获取的电影数组作为payload来执行dispatch操作，在<code>search</code>方法中我们实际上有3个不同的操作。</p>
<ul>
<li>SEARCH_MOVIES_REQUEST：更新状态对象，loading&#x3D;true，errorMessage&#x3D;false。</li>
<li>SEARCH_MOVIES_SUCCESS：如果请求成功，那么更新状态，loading&#x3D;false，movies&#x3D;a_ction.payload。payload是从OMDB获取到的电影搜索结果。</li>
<li>SEARCH_MOVIES_FAILURE：请求失败的话，loading&#x3D;false，errorMessage&#x3D;action.error。error也是服务器返回的错误消息。</li>
</ul>
<h3 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h3><p>至此我们整个项目做完了，用到了<strong>useState</strong>、<strong>useReducer</strong>、<strong>useEffect</strong>三个hooks。对React hooks的用法有了一个基本的了解，更多详细的内容推荐去官网阅读。</p>
<blockquote>
<p>原文链接:<br><a target="_blank" rel="noopener" href="https://www.freecodecamp.org/news/how-to-build-a-movie-search-app-using-react-hooks-24eb72ddfaf7/">https://www.freecodecamp.org/news/how-to-build-a-movie-search-app-using-react-hooks-24eb72ddfaf7/</a></p>
</blockquote>

    </div>

    
    
    
    
      <div>
        <div>
    
        <div style="text-align:center;color: #ccc;font-size:16px;">-------------本文结束<i class="fa fa-bolt"></i>感谢阅读-------------</div>
    
</div>
      </div>
    
        

<div>
<ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者： </strong>右眼
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="https://jjbond.cn/posts/13078.html" title="用React Hooks搭建一个电影搜索App">https://jjbond.cn/posts/13078.html</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" rel="noopener" target="_blank"><i class="fab fa-fw fa-creative-commons"></i>BY-NC-SA</a> 许可协议。转载请注明出处！
  </li>
</ul>
</div>


      <footer class="post-footer">
          
          <div class="post-tags">
              <a href="/tags/Web/" rel="tag"><i class="fa fa-tag"></i> Web</a>
              <a href="/tags/React/" rel="tag"><i class="fa fa-tag"></i> React</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/posts/2492.html" rel="prev" title="youyan">
      <i class="fa fa-chevron-left"></i> youyan
    </a></div>
      <div class="post-nav-item">
    <a href="/posts/958.html" rel="next" title="用nodejs编写一个淘宝秒杀脚本">
      用nodejs编写一个淘宝秒杀脚本 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          
    
  <div class="comments">
    <div id="lv-container" data-id="city" data-uid="MTAyMC81ODY4My8zNTE0NQ=="></div>
  </div>
  

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#App-%E5%AE%8C%E6%88%90%E5%90%8E%E7%9A%84%E6%95%88%E6%9E%9C%E9%A2%84%E8%A7%88"><span class="nav-number">1.</span> <span class="nav-text">App 完成后的效果预览</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E9%A1%B9%E7%9B%AE%E7%94%A8%E5%88%B0%E7%9A%84%E5%B7%A5%E5%85%B7"><span class="nav-number">2.</span> <span class="nav-text">项目用到的工具</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E6%9E%84%E6%88%90%E8%AF%A5-App-%E7%9A%84-4-%E4%B8%AA%E7%BB%84%E4%BB%B6"><span class="nav-number">3.</span> <span class="nav-text">构成该 App 的 4 个组件</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%BC%80%E5%A7%8B%E7%9D%80%E6%89%8B%E6%9E%84%E5%BB%BA%E6%88%91%E4%BB%AC%E7%9A%84-APP"><span class="nav-number">4.</span> <span class="nav-text">开始着手构建我们的 APP</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Hooks-API-useState%E4%BB%8B%E7%BB%8D"><span class="nav-number">5.</span> <span class="nav-text">Hooks API - useState介绍</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E6%80%BB%E7%BB%93"><span class="nav-number">6.</span> <span class="nav-text">总结</span></a></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="右眼"
      src="/images/avatar.png">
  <p class="site-author-name" itemprop="name">右眼</p>
  <div class="site-description" itemprop="description">任何时间 任何地点<br>超级侦探 认真办案</div>
</div>


<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">18</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">6</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">7</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="https://github.com/Neopo1itan/" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;Neopo1itan&#x2F;" rel="noopener" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
      <span class="links-of-author-item">
        <a href="https://weibo.com/youyan030" title="Weibo → https:&#x2F;&#x2F;weibo.com&#x2F;youyan030" rel="noopener" target="_blank"><i class="fab fa-weibo fa-fw"></i>Weibo</a>
      </span>
      <span class="links-of-author-item">
        <a href="https://steamcommunity.com/id/youyanww/" title="Steam → https:&#x2F;&#x2F;steamcommunity.com&#x2F;id&#x2F;youyanww&#x2F;" rel="noopener" target="_blank"><i class="fab fa-steam fa-fw"></i>Steam</a>
      </span>
      <span class="links-of-author-item">
        <a href="https://space.bilibili.com/895680/video" title="BiliBili → https:&#x2F;&#x2F;space.bilibili.com&#x2F;895680&#x2F;video" rel="noopener" target="_blank"><i class="fa fa-wheelchair fa-fw"></i>BiliBili</a>
      </span>
  </div>



      </div>
      
<iframe frameborder="no" border="0" marginwidth="0" marginheight="0" width=320 height=240 src="//music.163.com/outchain/player?type=0&id=8545160772&auto=1&height=430"></iframe>
    
      <script type="text/javascript" charset="utf-8" src="/js/tagcloud.js"></script>
      <script type="text/javascript" charset="utf-8" src="/js/tagcanvas.js"></script>
        <div class="widget-wrap">
          <div id="myCanvasContainer" class="widget tagcloud">
            <canvas width="250" height="250" id="resCanvas" style="width:100%">
              <ul class="tag-list" itemprop="keywords"><li class="tag-list-item"><a class="tag-list-link" href="/tags/JS/" rel="tag">JS</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/JavaScript/" rel="tag">JavaScript</a><span class="tag-list-count">5</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/React/" rel="tag">React</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/Vue/" rel="tag">Vue</a><span class="tag-list-count">5</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/Web/" rel="tag">Web</a><span class="tag-list-count">15</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/nodejs/" rel="tag">nodejs</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/python/" rel="tag">python</a><span class="tag-list-count">1</span></li></ul>
            </canvas>
          </div>
        </div>
    
    </div>

  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2024</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">右眼</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-chart-area"></i>
    </span>
    <span title="站点总字数">59k</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-coffee"></i>
    </span>
    <span title="站点阅读时长">53 分钟</span>
</div>
  <div class="powered-by">
    <!--由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.org/" class="theme-link" rel="noopener" target="_blank">NexT.Gemini</a> 强力驱动 -->
    <span>个人网站&nbsp&nbsp&nbsp|&nbsp&nbsp&nbsp吉吉邦德</span>
  </div>



<!--添加运行时间--> 
</br>
<span id="sitetime"></span> 
<script language=javascript> 
  function siteTime(){ 
    window.setTimeout("siteTime()", 1000); 
    var seconds = 1000; 
    var minutes = seconds * 60; 
    var hours = minutes * 60; 
    var days = hours * 24; 
    var years = days * 365; 
    var today = new Date(); 
    var todayYear = today.getFullYear(); 
    var todayMonth = today.getMonth()+1; 
    var todayDate = today.getDate(); 
    var todayHour = today.getHours(); 
    var todayMinute = today.getMinutes(); 
    var todaySecond = today.getSeconds(); 
    /* 
    Date.UTC() -- 返回date对象距世界标准时间(UTC)1970年1月1日午夜之间的毫秒数(时间戳) 
    year - 作为date对象的年份，为4位年份值 
    month - 0-11之间的整数，做为date对象的月份 
    day - 1-31之间的整数，做为date对象的天数 
    hours - 0(午夜24点)-23之间的整数，做为date对象的小时数 
    minutes - 0-59之间的整数，做为date对象的分钟数 
    seconds - 0-59之间的整数，做为date对象的秒数 
    microseconds - 0-999之间的整数，做为date对象的毫秒数 
    */ 
    var t1 = Date.UTC(2023,07,06,15,49,36); //北京时间2018-2-13 00:00:00 
    var t2 = Date.UTC(todayYear,todayMonth,todayDate,todayHour,todayMinute,todaySecond); 
    var diff = t2-t1; 
    var diffYears = Math.floor(diff/years); 
    var diffDays = Math.floor((diff/days)-diffYears*365); 
    var diffHours = Math.floor((diff-(diffYears*365+diffDays)*days)/hours); 
    var diffMinutes = Math.floor((diff-(diffYears*365+diffDays)*days-diffHours*hours)/minutes); 
    var diffSeconds = Math.floor((diff-(diffYears*365+diffDays)*days-diffHours*hours-diffMinutes*minutes)/seconds); 
    document.getElementById("sitetime").innerHTML=" 已运行"+/*diffYears+" 年 "+*/diffDays+" 天 "+diffHours+" 小时 "+diffMinutes+" 分钟 "+diffSeconds+" 秒"; 
    } 
    siteTime(); 
</script> 
<!--// 添加运行时间-->

        








      </div>
    </footer>
  </div>

  
  <script type="text/javascript" src="//cdn.bootcss.com/canvas-nest.js/1.0.0/canvas-nest.min.js"></script>
    

  
  <script src="/lib/anime.min.js"></script>
  <script src="/lib/pjax/pjax.min.js"></script>
  <script src="//cdn.jsdelivr.net/npm/lozad@1/dist/lozad.min.js"></script>
  <script src="/lib/velocity/velocity.min.js"></script>
  <script src="/lib/velocity/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/pisces.js"></script>


<script src="/js/next-boot.js"></script>

  <script>
var pjax = new Pjax({
  selectors: [
    'head title',
    '#page-configurations',
    '.content-wrap',
    '.post-toc-wrap',
    '.languages',
    '#pjax'
  ],
  switches: {
    '.post-toc-wrap': Pjax.switches.innerHTML
  },
  analytics: false,
  cacheBust: false,
  scrollTo : !CONFIG.bookmark.enable
});

window.addEventListener('pjax:success', () => {
  document.querySelectorAll('script[data-pjax], script#page-configurations, #pjax script').forEach(element => {
    var code = element.text || element.textContent || element.innerHTML || '';
    var parent = element.parentNode;
    parent.removeChild(element);
    var script = document.createElement('script');
    if (element.id) {
      script.id = element.id;
    }
    if (element.className) {
      script.className = element.className;
    }
    if (element.type) {
      script.type = element.type;
    }
    if (element.src) {
      script.src = element.src;
      // Force synchronous loading of peripheral JS.
      script.async = false;
    }
    if (element.dataset.pjax !== undefined) {
      script.dataset.pjax = '';
    }
    if (code !== '') {
      script.appendChild(document.createTextNode(code));
    }
    parent.appendChild(script);
  });
  NexT.boot.refresh();
  // Define Motion Sequence & Bootstrap Motion.
  if (CONFIG.motion.enable) {
    NexT.motion.integrator
      .init()
      .add(NexT.motion.middleWares.subMenu)
      .add(NexT.motion.middleWares.postList)
      .bootstrap();
  }
  NexT.utils.updateSidebarPosition();
});
</script>


  <script defer src="/lib/three/three.min.js"></script>
    <script defer src="/lib/three/three-waves.min.js"></script>


  




  
<script src="/js/local-search.js"></script>













    <div id="pjax">
  

  

<script>
NexT.utils.loadComments(document.querySelector('#lv-container'), () => {
  window.livereOptions = {
    refer: location.pathname.replace(CONFIG.root, '').replace('index.html', '')
  };
  (function(d, s) {
    var j, e = d.getElementsByTagName(s)[0];
    if (typeof LivereTower === 'function') { return; }
    j = d.createElement(s);
    j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
    j.async = true;
    e.parentNode.insertBefore(j, e);
  })(document, 'script');
});
</script>

    </div>

        <style>
            [bg-lazy] {
                background-image: none !important;
                background-color: #eee !important;
            }
        </style>
        <script>
            window.imageLazyLoadSetting = {
                isSPA: true,
                preloadRatio: 1,
                processImages: null,
            };
        </script><script>window.addEventListener("load",function(){var t=/\.(gif|jpg|jpeg|tiff|png)$/i,r=/^data:image\/[a-z]+;base64,/;Array.prototype.slice.call(document.querySelectorAll("img[data-original]")).forEach(function(a){var e=a.parentNode;"A"===e.tagName&&(e.href.match(t)||e.href.match(r))&&(e.href=a.dataset.original)})});</script><script>!function(r){r.imageLazyLoadSetting.processImages=t;var e=r.imageLazyLoadSetting.isSPA,n=r.imageLazyLoadSetting.preloadRatio||1,c=a();function a(){var t=Array.prototype.slice.call(document.querySelectorAll("img[data-original]")),e=Array.prototype.slice.call(document.querySelectorAll("[bg-lazy]"));return t.concat(e)}function t(){e&&(c=a());for(var t,o=0;o<c.length;o++)0<=(t=(t=c[o]).getBoundingClientRect()).bottom&&0<=t.left&&t.top<=(r.innerHeight*n||document.documentElement.clientHeight*n)&&function(){var t,e,n,a,i=c[o];e=function(){c=c.filter(function(t){return i!==t}),r.imageLazyLoadSetting.onImageLoaded&&r.imageLazyLoadSetting.onImageLoaded(i)},(t=i).hasAttribute("bg-lazy")?(t.removeAttribute("bg-lazy"),e&&e()):(n=new Image,a=t.getAttribute("data-original"),n.onload=function(){t.src=a,t.removeAttribute("data-original"),e&&e()},t.src!==a&&(n.src=a))}()}function i(){clearTimeout(t.tId),t.tId=setTimeout(t,500)}t(),document.addEventListener("scroll",i),r.addEventListener("resize",i),r.addEventListener("orientationchange",i)}(this);</script><script async>window.onload=function(){var a=document.createElement('script'),b=document.getElementsByTagName('script')[0];a.type='text/javascript',a.async=!0,a.src='/sw-register.js?v='+Date.now(),b.parentNode.insertBefore(a,b)};</script></body></html>